import React, { useState } from 'react';
import type { FormEvent } from 'react';
import { message } from 'antd';
import { login } from './api';
import './LoginPage.css';
import { useStore } from './store'
const LoginPage = () => {
  const [username, setUsername] = useState('admin');
  const [password, setPassword] = useState('123456');
  const [rememberMe, setRememberMe] = useState(false);
  const [loading, setLoading] = useState(false);
  const { setTokenInfo } = useStore();
  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const { code, data, msg } = await login(username, password);
      if (code == 0) {
        setTokenInfo(data);
        message.success('登录成功');
        window.location.href = '/'
      } else {
        message.error(msg);
      }

    } catch (error: unknown) {
      if (error instanceof Error) {
        message.error(error.message || '登录失败');
      } else {
        message.error('登录失败');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <div className="login-header">
        <h1>AI知行学堂</h1>
        <p>AI+X 智学习课，培养实战型复合人才</p>
      </div>

      <div className="login-tabs">
        <button className="active">学生登录</button>
        <button>教师登录</button>
      </div>

      <form onSubmit={handleSubmit} className="login-form">
        <div className="form-group">
          <label htmlFor="username">用户名</label>
          <input
            type="text"
            id="username"
            placeholder="请输入用户名"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            required
          />
        </div>

        <div className="form-group">
          <label htmlFor="password">密码</label>
          <input
            type="password"
            id="password"
            placeholder="请输入密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </div>

        <div className="form-options">
          <label className="remember-me">
            <input
              type="checkbox"
              checked={rememberMe}
              onChange={(e) => setRememberMe(e.target.checked)}
            />
            记住我
          </label>
          <a href="#forgot-password" className="forgot-password">忘记密码？</a>
        </div>

        <button
          type="submit"
          className="login-button"
          disabled={loading}
        >
          {loading ? '登录中...' : '登录'}
        </button>
      </form>

      <div className="login-footer">
        <p>还没有账号？<a href="#register">立即注册</a></p>
        <p><a href="#teacher-account">使用教师领取账户</a></p>
        <p className="version-info">系统演示版本</p>
      </div>
    </div>
  );
};

export default LoginPage;
